// const app = require('express')()

//导入数据库操作模块
const db = require("../../db/index.js")

// 格式化时间
var moment = require('moment')



/**
 * 获取成员列表
 * @param {*} req 
 * @param {*} res 
 */
exports.getMemberList = (req, res) => {
    const Admin = req.data
    if (Admin.level == '3') {
        console.log('没有权限，Admin.level ===> ' + Admin.level)
        return res.send({
            code: 403,
            msg: '对不起，没有权限！',
            data: {}
        })
    }
    let sql = ''
    let department = req.query.department
    let name = req.query.name
    let size = parseInt(req.query.limit)
    let start = (parseInt(req.query.page) - 1) * size
    let sqlArr = []
    if (!name || name == "") {
        if (!department || department == "" || department + "" == "全部") {
            sql = `SELECT COUNT(*) FROM xks_member WHERE status != 0;
            SELECT * FROM xks_member WHERE status != 0 limit ?,?`;
            sqlArr = [start, size]
        }
        else {
            sql = `SELECT COUNT(*) FROM xks_member WHERE status != 0 AND department = ?;
            SELECT * FROM xks_member WHERE status != 0 AND department = ? limit ?,?`;
            sqlArr = [department, department, start, size]
        }

        db.query(sql, sqlArr, (err, results) => {
            if (err) {
                return res.send({
                    code: 505,
                    msg: '错误',
                    videos: {}
                })
            }
            // 计算总页数
            var allCount = results[0][0]['COUNT(*)'];
            // console.log('results[0],', results[0])
            var allPage = parseInt(allCount) / size;
            var pageStr = allPage.toString();
            // 不能被整除
            if (pageStr.indexOf('.') > 0) {
                allPage = parseInt(pageStr.split('.')[0]) + 1;
            }
            var list = results[1];
            return res.send({
                code: 200,
                msg: '成功',
                totalPages: allPage,
                total: allCount,
                currentPage: start + 1,
                data: list
            })
        })
    } else {
        if (!department || department == "" || department == "全部") {
            sql = `SELECT COUNT(*) FROM xks_member WHERE status != 0 AND name LIKE concat('%',?, '%');
            SELECT * FROM xks_member WHERE status != 0 AND name LIKE concat('%',?, '%') limit ?,?`;
            sqlArr = [name, name, start, size]
        } else {
            sql = `SELECT COUNT(*) FROM xks_member WHERE status != 0 AND name LIKE concat('%',?, '%') AND department = ?;
            SELECT * FROM xks_member WHERE status != 0 AND name LIKE concat('%',?, '%') AND department = ? limit ?,?`;
            sqlArr = [name, department, name, department, start, size]
        }
        db.query(sql, sqlArr, (err, results) => {
            if (err) {
                return res.send({
                    code: 505,
                    msg: '错误',
                    videos: {}
                })
            }
            // 计算总页数
            var allCount = results[0][0]['COUNT(*)'];
            // console.log('results[0],', results[0])
            var allPage = parseInt(allCount) / size;
            var pageStr = allPage.toString();
            // 不能被整除
            if (pageStr.indexOf('.') > 0) {
                allPage = parseInt(pageStr.split('.')[0]) + 1;
            }
            var list = results[1];
            return res.send({
                code: 200,
                msg: '成功',
                totalPages: allPage,
                total: allCount,
                currentPage: start + 1,
                data: list
            })
        })
    }
}

/**
 * 增加成员
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.addMember = (req, res) => {
    // 判断是否有操作的权限
    const Admin = req.data
    if (Admin.level == '3') {
        console.log('没有权限，Admin.level ===> ' + Admin.level)
        return res.send({
            code: 403,
            msg: '对不起，没有权限！',
            data: {}
        })
    }
    const Member_info = req.body;
    if (JSON.stringify(Member_info) == "{}") {
        console.log('【增加成员发送错误】' + 'req.body ===> ', req.body)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    else {
        if (!Member_info.name || !Member_info.phone || !Member_info.department) {
            return res.send({
                code: 400,
                msg: '有必填字段未填，请重新操作。',
                data: {}
            })
        }
    }

    //创建时间
    let nowTime = new Date()
    var formatTime = moment(nowTime).format('YYYY-MM-DD HH:mm')
    Member_info['create_time'] = formatTime;

    const addSql = `INSERT INTO xks_member SET ? `
    db.query(addSql, Member_info, (err, result) => {
        if (err) {
            console.log(err.message)
            return res.send({
                code: 505,
                msg: err.message,
                data: {}
            })
        }
        if (result.affectedRows !== 1) {
            return res.send({
                code: 500,
                msg: '增加失败，请稍后再试！',
                data: {}
            })
        }
        res.send({
            code: 200,
            msg: '增加成功',
            data: result.affectedRows
        })
    })

}


/**
 * 删除成员
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.delMember = (req, res) => {
    // 判断是否有操作的权限
    const Member = req.data
    if (Member.level == '3') {
        console.log('【删除成员】没有权限，Member.level ===> ' + Member.level)
        return res.send({
            code: 403,
            msg: '对不起，没有权限！',
            data: {}
        })
    }

    const Member_info = req.query;
    if (JSON.stringify(Member_info) == "{}") {
        console.log('【删除成员发送错误】' + 'req.body ===> ', req.query)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    else {
        if (!Member_info.id) {
            return res.send({
                code: 400,
                msg: '有必填字段未填，请重新操作。',
                data: {}
            })
        }
    }
    const delSql = `UPDATE xks_member SET status = 0 WHERE id = ?`
    db.query(delSql, Member_info.id, (err, result) => {
        if (err) {
            console.log(err.message)
            return res.send({
                code: 505,
                msg: err.message,
                data: {}
            })
        }
        if (result.affectedRows !== 1) {
            return res.send({
                code: 500,
                msg: '删除失败，请检查ID是否有误！',
                data: {}
            })
        }
        res.send({
            code: 200,
            msg: '删除成功！',
            data: {}
        })
    })

}


/**
 * 更新成员
 * @param {*} req 
 * @param {*} res 
 * @returns 
 */
exports.updateMember = (req, res) => {
    // 判断是否有操作的权限
    const Member = req.data
    if (Member.level == '3') {
        console.log('没有权限，Member.level ===> ' + Member.level)
        return res.send({
            code: 403,
            msg: '对不起，没有权限！',
            data: {}
        })
    }

    const Member_info = req.body;
    if (JSON.stringify(Member_info) == "{}") {
        console.log('【更新成员发送错误】' + 'req.body ===> ', req.body)
        return res.send({
            code: 400,
            msg: '因发送的请求语法错误,服务器无法正常读取。',
            data: {}
        })
    }
    else {
        if (!Member_info.id || !Member_info.phone || !Member_info.name) {
            return res.send({
                code: 400,
                msg: '有必填字段未填，请重新操作。',
                data: {}
            })
        }
    }
    const id = Member_info.id

    delete Member_info.id
    const updateSql = `UPDATE xks_member SET ? WHERE status != 0 AND id = ?`
    db.query(updateSql, [Member_info, id], (err, result) => {
        if (err) {
            console.log(err.message)
            return res.send({
                code: 505,
                msg: err.message,
                data: {}
            })
        }
        if (result.affectedRows !== 1) {
            return res.send({
                code: 500,
                msg: '更新失败，请稍后再试！',
                data: {}
            })
        }
        res.send({
            code: 200,
            msg: '更新成功',
            data: result.affectedRows
        })
    })
}


exports.getDepartment = async (req, res) => {
    // console.log('获取学习视频列表'+req.ip)

    const sql = `SELECT DISTINCT department FROM xks_member WHERE status != 0`;
    await db.query(sql, (err, results) => {
        if (err) {
            return res.send({
                code: 505,
                msg: '发送了错误' + err.message,
                data: {}
            })
        }

        if (!results.length > 0) {
            return res.send({
                code: 400,
                msg: '没有找到数据',
                data: {}
            })
        }

        return res.send({
            code: 200,
            msg: '成功',
            data: results
        })
    })

}